<template>
    <!-- 支付宝绑定弹窗 -->
    <Modal
        width="820"
        class="er-modal er-alipay-recharge"
        :closable="false"
        :mask-closable="false"
        :value="show">

        <!-- 进度条 -->
        <div class="er-header" slot="header">
            <ol class="er-header__list">
                <li v-for="(item, key) in items" :key="key" :class="['er-header__item', {'active' : step >= key}]">
                    <a href="javascript:void 0" :class="{
                        'er-header__box': true,
                        'is-active': step >= key
                    }">{{item}}</a>
                </li>
            </ol>
            <div class="er-header__back" :style="{width: backWidth}"></div>
        </div>


        <!-- 弹窗尾部 -->
        <Row slot="footer">
            <Button type="text" @click="prev(step)">{{prevButtonName}}</Button>
            <Button type="primary" @click="next(step)" v-if="step < 3" :loading="submitLoading">{{nextButtonName}}</Button>
        </Row>

        <!-- 绑定swiper步骤 -->
        <Carousel v-model="step" dots="none" arrow="never" v-if="show">
            <!-- 选择用户账户类型 -->
            <CarouselItem>
                <div id="account">
                    <div class="accountTitle">
                        <p>选择账户类型</p>
                        <!-- 账户类型选择 -->
                        <div>
                            <RadioGroup v-model="type" type="button" size="large">
                                <Radio :label="item.value" v-for="(item, index) in types" :key="index" :disabled="status == 2 && item.value !== type">{{item.name}}</Radio>
                            </RadioGroup>
                        </div>
                    </div>

                    <p class="child-title">请准备以下资料</p>

                    <!-- 账户类型说明 -->
                    <div class="content">   
                        <div v-show="type === item.value" v-for="(item, index) in types" :key="index">
                            <p v-for="(note, sonIndex) in item.notes" :key="sonIndex">{{note}}</p>
                        </div>
                    </div>
               </div>
            </CarouselItem>

            <!-- 提交基本资料进行审核 -->
            <CarouselItem>
                <div id="baseDate">
                    <p class="title">提交基本资料</p>
                    <!-- 基础资料表单 -->
                    <Form
                        style="padding-left: 20px"
                        ref="data"
                        :model="baseData"
                        :rules="baseRules"
                        label-position="right"
                        :label-width="150"
                        :show-message="false">

                        <FormItem :label="baseNames[index]" :prop="item" v-for="(item, index) in baseKeys" :key="index">
                            <Input v-model.trim="baseData[item]" v-if="index + breakPoint + 1 <= baseKeys.length" :placeholder="notes[index]" :disabled="isDisable[item]"></Input>
                            <c-upload v-model="baseData[item]" v-if="index + breakPoint + 1 > baseKeys.length" :onlyFlag="'alipay'" :fileSize="2" :isAlipay="true" :imgKey="item" :branchId="branchId"></c-upload>
                        </FormItem>

                        <!-- 开户行 -->
                        <FormItem label="商户地址" prop="address" style="margin-bottom: 0px;">
                            <Row type="flex" :gutter="8">
                                <!-- 开户行所在省份 -->
                                <Col span="8">
                                    <Select placeholder="省(必填)" filterable  v-model="baseData.province">
                                        <Option v-for="item in provinces" :value="item.id" :key="item.name">{{ item.name }}</Option>
                                    </Select>
                                </Col>

                                 <!-- 开户行所在区域 -->
                                <Col span="8">
                                    <Select placeholder="市(必填)" v-model="baseData.city">
                                        <Option v-for="item in citys" :value="item.id" :key="item.id">{{ item.name }}</Option>
                                    </Select>
                                </Col>

                                <Col span="8">
                                    <Select placeholder="区(必填)" v-model="baseData.district">
                                        <Option v-for="item in countrys" :value="item.id" :key="item.id">{{ item.name }}</Option>
                                    </Select>
                                </Col>

                                <Col span="24" style="margin-top:20px;">
                                     <Input v-model="baseData.address" placeholder="必填,详细地址(56个字符以内)" clearable style="width: 100%" />
                                </Col>
                            </Row>
                        </FormItem>


                    </Form>
                </div>
            </CarouselItem>

            <CarouselItem>
                <div id="recieve-account">
                    <p class="title">设置收款账号</p>

                    <Form
                        style="padding-left: 20px; padding: 50px 0"
                        ref="bank"
                        :model="baseData"
                        :rules="recieveRules"
                        label-position="right"
                        :label-width="150"
                        :show-message="false">

                        <FormItem label="账户类型">
                            {{type > 2 ? '公司账户' : '个人账户'}}
                        </FormItem>

                        <FormItem :label="type == 3 ? '企业法人名称' : '持卡人姓名'">
                            {{type == 3 ? baseData.legal_person : baseData.principal_person}}
                        </FormItem>

                        <FormItem label="持卡人身份证号" v-if="type !== 3">
                            {{baseData.principal_cert_no}}
                        </FormItem>

                        <FormItem :label="bankName" prop="bank_card_no">
                           <i-input v-model.trim="baseData.bank_card_no" :placeholder="type == 3 ? '必填' : '填写的银行卡号必须是持卡人所有，否则打款失败'"></i-input>
                        </FormItem>

                        <FormItem label="银行开户名" prop="bank_cert_name">
                           <i-input v-model.trim="baseData.bank_cert_name" placeholder="必填"></i-input>
                        </FormItem>

                        <FormItem label="请输入验证码" prop="auth_code" v-if="type !== 3 && status !== 2" class="alipay-special">
                           <i-input v-model.trim="baseData.auth_code"></i-input>
                           <i-button @click="sentMobileCode" style="margin-left:10px;" :loading="buttonLoading">{{buttonLoading ? timeLimit + 's后可再次获取' : '获取手机验证码'}}</i-button>
                        </FormItem>

                        <FormItem label="所属联行号" prop="contact_line" class="special" v-if="type === 3">
                            <!-- <Select placeholder="" v-model="baseData.contact_line" filterable>
                                <Option v-for="item in banks" :value="item.pay_bank_id" :key="item.pay_bank_id">{{ item.name }} - {{ item.pay_bank_id }}</Option>
                            </Select> -->

                            <Select
                                filterable
                                clearable
                                remote
                                placeholder="必选，支持开户行名称 和 联行号关键字搜索"
                                :remote-method="bankSelectMethod"
                                v-model="baseData.contact_line"
                                :loading="loadingBank">
                                <Option v-for="item in banks" :value="item.contact_no" :key="item.contact_no">{{ item.bank_name }} - {{ item.contact_no }}</Option>
                            </Select>
                            备注: 填写的联行号必须正确，否则影响打款
                        </FormItem>
                    </Form>
                </div>
            </CarouselItem>
        </Carousel>

    </Modal>
</template>

<script>
import CUpload from '@/components/upload/upload'
import validate from '@/libs/validate.js'
import { http, api } from '@/libs/http'
import util from '@/libs/util'
import debounce from 'lodash/debounce'
const config = {
  key: ['merchant_name', 'alias', 'contact_name', 'contact_mobile', 'email', 'service_phone_no', 'principal_person', 'principal_mobile', 'principal_cert_no', 'cert_photo_a', 'cert_photo_b', 'shop_photo', 'shop_entrance_photo'],
  name: ['商户名称', '商户简称', '联系人姓名', '联系人手机号', '邮箱', '客服电话', '负责人姓名', '负责人手机号', '负责人身份证号', '负责人身份证正面', '负责人身份证反面', '店面门头照', '店铺内景照'],
  breakPoint: 4
}
export default {
  data () {
    return {
      config,
      items: ['选择身份类型', '提交基本资料', '设置收款账户'], // header步骤
      types: [
        {
          value: 1,
          name: '自然人',
          notes: [
            '(注:当前账户类型为自然人，没有营业执照的商户可通过此方式,收款到个人账户)',
            '1.个人身份证',
            '2.个人银行卡'
          ]
        },
        {
          value: 2,
          name: '个体工商户',
          notes: [
            '(注:当前账户类型为个体工商户，将收款到个人账户)',
            '1.个体户工商户类营业执照',
            '2.经营者本人身份证正反面',
            '3.经营者本人银行卡信息'
          ]
        },
        {
          value: 3,
          name: '企业工商户',
          notes: [
            '(注:当前账户类型为企业工商户，将收款到企业账户)',
            '1.企业工商户类营业执照',
            '2.法人代表身份证正反面',
            '3.企业对公收款银行账户'
          ]
        }
      ],
      buttonLoading: false, // 是否正在加载
      step: 0, // 当前Carousel所在位置
      type: 1, // 开通的账户类型 1 => 自然人 2 => 个体工商户 3 => 企业工商户
      baseData: {}, // swiper 第二栏基础资料
      baseRules: {},
      baseKeys: {},
      notes: [], // 备注
      baseNames: {},
      recieveRules: {
        bank_card_no: [{ required: true }],
        bank_cert_name: [{ required: true, validator: validate.validPrincipalPerson }],
        auth_code: [{ required: true }],
        contact_line: [{ required: true }]
      },
      loadingBank: false, // 搜索loading
      breakPoint: 2,
      banks: [],
      poundage_type: 1,
      provinces: [], // 省
      citys: [], // 市
      countrys: [], // 区
      Timer: null,
      timeLimit: 60,
      isDisable: [],
      submitLoading: false // 提交是否正在加载
    }
  },

  components: {CUpload},

  watch: {
    province (value) {
      if (value) {
        this.getPayCitys(value)
      }
      // this.baseData.city = '';
      // this.baseData.district = '';
    },

    city (value) {
      if (value) {
        this.getPayCountys(value)
      }
      // this.baseData.district = '';
    },

    type (value) {
      this.construcKeyAndName(value)
      this.dataParams = {}
    },

    step (value) {
      const $dom = document.querySelector('.ivu-carousel-track')

      if (value === 0) {
        $dom.style.maxHeight = '487px'
      } else if (value === 1) {
        if (this.type === 1) {
          $dom.style.maxHeight = '982px'
        } else if (this.type === 2) {
          $dom.style.maxHeight = '1102px'
        } else {
          $dom.style.maxHeight = '1282px'
        }
      } else {
        $dom.style.maxHeight = this.type !== 3 ? '539px' : '520px'
      }
    },

    dataParams (value, oldVal) {
      this.constructionData()
    }
  },

  computed: {
    bankName () {
      if (this.type === 3) {
        return '企业账号'
      }
      return '银行卡号'
    },

    province () {
      return this.baseData.province
    },

    city () {
      return this.baseData.city
    },

    backWidth () {
      return (this.step + 1) * 33.333 + '%'
    },

    /**
         * 上一步按钮文案
         */
    prevButtonName () {
      if (this.step === 0) {
        return '取消'
      } else {
        return '上一步'
      }
    },

    /**
         * 下一步按钮文案
         */
    nextButtonName () {
      if (this.step === 0) {
        return '确定'
      } else if (this.step === 1) {
        return '下一步'
      } else {
        return this.status === 2 ? '重新提交' : '提交申请'
      }
    }
  },

  mounted () {
    this.getPayProvinces()
    this.constructionData()
  },

  props: {
    show: {
      required: true,
      type: Boolean
    },
    dataParams: {
      type: Object,
      required: true
    },
    status: {
      required: true
    },
    branchId: {
      required: false,
      default: 0
    }
  },

  methods: {
    bankSelectMethod: debounce(function (query) {
      if (query !== '') {
        const params = {
          keyword: query,
          platform: 2
        }
        this.loadingBank = true
        http.request(this, api.pay_banks, null, params, res => {
          if (res) {
            this.banks = res
          }
          this.loadingBank = false
        })
      } else {
        this.banks = []
      }
    }, 300),

    /**
         * 获取所有的省份
         */
    getPayProvinces () {
      http.request(this, api.pay_provinces, null, {platform: 2}, res => {
        if (res) {
          this.provinces = res
        }
      })
    },

    /**
        * 获取该省份所有城市
        */
    getPayCitys (id) {
      if (!id) {
        return
      }
      const params = {
        platform: 2,
        parent_id: id
      }
      http.request(this, api.pay_citys, null, params, res => {
        if (res) {
          this.citys = res
        }
      })
    },

    /**
        * 获取该城市所有区域
        */
    getPayCountys (id) {
      if (!id) {
        return
      }
      const params = {
        platform: 2,
        parent_id: id
      }
      http.request(this, api.pay_country, null, params, res => {
        if (res) {
          this.countrys = res
        }
      })
    },

    /**
        * 发放手机验证码
        */
    sentMobileCode () {
      if (this.baseData.principal_mobile.length !== 11) {
        this.$Message.error('请输入11位的手机号码')
        return
      }

      http.request(this, api.alipay_code, null, {phone_num: this.baseData.principal_mobile}, res => {
        if (res) {
          this.$Message.info('短信验证码已下发')
          this.timeLimit = 60
          this.Timer = setInterval(() => {
            if (this.timeLimit === 0) {
              clearInterval(this.Timer)
              this.buttonLoading = false
            }
            this.timeLimit--
          }, 1000)
          this.buttonLoading = true
        }
      })
    },

    /**
        * 构造三种情况的字段
        */
    construcKeyAndName (type) {
      let breakPoint
      let name

      let keys = ['merchant_name', 'alias', 'contact_name', 'contact_mobile', 'email', 'service_phone_no', 'principal_person', 'principal_mobile', 'principal_cert_no', 'cert_photo_a', 'cert_photo_b', 'shop_photo', 'shop_entrance_photo']
      let baseNames = ['商户名称', '商户简称', '联系人姓名', '联系人手机号', '邮箱', '客服电话']
      let names = ['姓名', '手机号', '身份证号', '身份证正面', '身份证反面', '店面门头照', '店铺内景照']

      if (type === 1) {
        name = '负责人'
        breakPoint = 4
      } else if (type === 2) {
        name = '经营者'
        breakPoint = 5
        baseNames.push('工商注册号')
        keys.splice(6, 0, 'buss_auth_num')
      } else {
        name = '法人代表'
        breakPoint = 7
        baseNames.push('工商注册号', '企业法人名称')
        keys.splice(6, 0, 'buss_auth_num', 'legal_person')
      }

      names = names.map((value, index) => {
        return value !== '店面门头照' ? name + value : value
      })

      let allNames = [...baseNames, ...names]

      if (type === 2) {
        allNames.push('营业执照')
        keys.push('license_photo')
      }

      if (type === 3) {
        const addtionalKeyArr = ['license_photo', 'prg_photo', 'industry_license_photo']
        const addtionalNameArr = ['营业执照', '组织机构代码', '开户许可证']
        allNames.push(...addtionalNameArr)
        keys.push(...addtionalKeyArr)
      }

      this.config = {
        key: keys,
        name: allNames,
        breakPoint
      }
    },

    /**
        * 构造表单数据
        */
    constructionData () {
      const { key, name, breakPoint } = this.config

      const hasParams = !!this.dataParams.account_type

      if (hasParams) {
        // const { poundage_type, account_type } = this.dataParams;
        const { merchant_type } = this.dataParams
        this.type = Number(merchant_type)
        // this.poundage_type = poundage_type;
      }

      let obj = {}
      let notes = []
      let isDisable = []
      let rules = {
        address: [
          {
            required: true,
            type: 'string',
            max: 56
          }
        ]
      }
      key.forEach((value, index) => {
        if (index + breakPoint + 1 > key.length) { // 如果是需要上传图片的需求全部重置
          obj[value] = ''

          rules[value] = hasParams && this.status === 2 ? { required: false } : {
            required: true
            // validator: validate.validFileObject
          }

          if (hasParams && this.status === 2 && (value === 'shop_photo' || value === 'shop_entrance_photo')) {
            const { pics: { ShopPhoto, ShopEntrancePhoto } } = this.dataParams

            if (Object.keys(this.dataParams.pics).length && (!ShopPhoto && !ShopEntrancePhoto)) { // 只要判断这两个值都没有都情况
              rules['shop_photo'] = !ShopPhoto ? {
                required: true
                // validator: validate.validFileObject
              } : { required: false }

              rules['shop_entrance_photo'] = !ShopEntrancePhoto ? {
                required: true
                // validator: validate.validFileObject
              } : { required: false }
            }
          }

          isDisable[value] = false
        } else {
          obj[value] = hasParams ? this.dataParams[value] : ''
          rules[value] = this.constructRule(value)
          if (this.status === 2 && (value === 'merchant_name' || value === 'principal_person' || value === 'principal_mobile' || value === 'principal_cert_no' || value === 'buss_auth_num' || value === 'legal_person')) {
            isDisable[value] = true
          } else {
            isDisable[value] = false
          }
        }
        notes.push(this.constructNote(value))
      })

      const commonKey = ['province', 'city', 'district', 'address', 'bank_card_no', 'bank_cert_name']

      if (this.type === 3) {
        commonKey.push('contact_line')
      } else {
        obj['auth_code'] = '' // 不管是修改还是重新提交都重置验证码
      }

      commonKey.forEach(value => {
        if (hasParams) {
          obj[value] = (value === 'province' || value === 'city' || value === 'district') ? Number(this.dataParams[value]) : this.dataParams[value]
        } else {
          obj[value] = ''
        }
        isDisable[value] = false
      })

      this.baseData = obj
      this.baseRules = rules
      this.baseKeys = key
      this.isDisable = isDisable
      this.notes = notes
      this.baseNames = name
      this.breakPoint = breakPoint
    },

    /**
        * 构造备注
        */
    constructNote (key) {
      let note = '必填'
      if (key === 'contact_mobile' || key === 'principal_mobile') {
        note += ', 11位数字的手机号码'
      } else if (key === 'email') {
        note += ', 请输入正确的电子邮箱地址'
      } else if (key === 'service_phone_no') {
        note += ', 5-15位电话号码，不能带-'
      } else if (key === 'principal_cert_no') {
        note += ', 18位身份证号'
      } else if (key === 'merchant_name') {
        if (this.type === 1) {
          note += ', 请填写负责人姓名或者公寓名称 (30个字符内)'
        } else {
          note += ', 必须与营业执照上的名称保持一致 (30个字符内)'
        }
      } else if (key === 'alias') {
        note += ', 20个字符以内'
      } else if (key === 'contact_name') {
        note += ', 10个字符以内'
      } else if (key === 'principal_person') {
        if (this.type === 2) {
          note += ', 必须要与营业执照上的经营者姓名保持一致'
        } else {
          note += ', 56个字符以内'
        }
      } else if (key === 'buss_auth_num') {
        note += ', 15位或者18字符'
      } else if (key === 'legal_person') {
        note += ', 请填写公司名称'
      }
      return note
    },

    /**
        * 构造相应的规则
        */
    constructRule (key) {
      if (key === 'contact_mobile' || key === 'principal_mobile') {
        return [{
          required: true,
          validator: validate.validPhone
        }]
      } else if (key === 'email') {
        return [{
          required: true,
          validator: validate.validEmail
        }]
      } else if (key === 'service_phone_no') {
        return [{
          required: true,
          validator: validate.validSerivicePhone
        }]
      } else if (key === 'principal_cert_no') {
        return [{
          required: true,
          validator: validate.validIDCard
        }]
      } else if (key === 'merchant_name') {
        return [{
          required: true,
          type: 'string',
          max: 30
        }]
      } else if (key === 'alias') {
        return [{
          required: true,
          type: 'string',
          max: 20
        }]
      } else if (key === 'contact_name') {
        return [{
          required: true,
          type: 'string',
          max: 10
        }]
      } else if (key === 'principal_person') {
        return [{
          required: true,
          type: 'string',
          max: 56
        }]
      } else if (key === 'buss_auth_num') {
        return [{
          required: true,
          validator: validate.validBussAuthNum
        }]
      } else {
        return [{
          required: true
        }]
      }
    },

    /**
         * 上一步
         */
    prev (step) {
      if (!this.step) {
        this.setVisibility(false)
        return
      }
      this.step--
    },

    /**
         * 打开或者关闭弹窗
         */
    setVisibility (val = false) {
      this.$emit('update:show', val)
      this.step = 0
    },

    /**
         * 下一步
         */
    next (step) {
      if (this.step === 1) { // 检查表单数据
        this.checkForm()
      } else if (this.step === 2) { // 提交表单数据
        this.handleSubmit()
      } else {
        this.step++
      }
    },

    /**
        *  检查表单数据
        */
    checkForm () {
      this.$refs['data'].validate((valid) => {
        if (!valid || this.baseData.address.length > 56) {
          this.$Message.error('请按照提示完整填写申请材料')
          return
        }

        this.step++
      })
    },

    /**
        *  提交表单数据
        */
    handleSubmit: util.throttle(function () {
      this.$refs['bank'].validate((valid) => {
        if (this.type !== 3) {
          if (this.baseData.bank_cert_name !== this.baseData.principal_person) { // 如果不为企业工商户，银行账户户名要和姓名一致
            this.$Message.error('银行户名必须和持卡人姓名一致')
            return
          }
        } else {
          if (this.baseData.bank_cert_name !== this.baseData.legal_person) {
            this.$Message.error('银行户名必须和企业法人名称一致')
            return
          }
        }
        if (!valid || (this.type === 3 && this.baseData.contact_line === '')) {
          this.$Message.error('请完整填写收款账号信息')
          return
        }
        this.baseData.merchant_type = '0' + this.type

        const { alipay_merchant_register, alipay_merchant_update } = api

        const reqApi = this.status === 2 ? alipay_merchant_update : alipay_merchant_register

        if (this.branchId) {
          this.baseData.branch_id = this.branchId
        }

        this.submitLoading = true
        http.request(this, reqApi, null, this.baseData, (res, error) => {
          this.submitLoading = false
          if (!error && res) { // 如果alipay 接口出问题，曝出相应错误
            this.$Message.success('提交成功')
            this.setVisibility()
            this.$emit('refresh')
          }
        })
      })
    })
  }
}
</script>
<style lang='less' scoped>
#account {
    p {
        text-align: center;
        margin-bottom: 10px;
    }
    .child-title {
        font-size: 22px;
        padding-top: 110px;
    }
    .content {
        margin-bottom: 70px; 
    }
}
.accountTitle {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    border-bottom: 1px solid rgba(0, 0, 0, 0.2);
    padding-top: 20px;

    p {
        font-size: 22px;
        padding-bottom: 20px;
        margin: 0px!important;
        box-sizing: border-box;
        padding-top: 8px;
    }
}
.title {
    font-size: 22px;
    text-align: left !important;
    padding: 20px 0;
    border-bottom: 1px solid rgba(0, 0, 0, 0.2);
    margin-bottom: 20px !important;
}
.wrap {
    display: flex;
    justify-content: center;
}
</style>